////
////  AddDeviceView.swift
////  casdon_swiftUI
////
////  Created by ww on 2025/5/9.
////
//
//
import SwiftUI
import FlowStacks

struct AddDeviceView: View {
    @EnvironmentObject var navigator: FlowNavigator<HomeStack>
    @StateObject var viewModel = AddDeviceViewModel()
    @State private var allowInnerScroll = false
    @State private var scanning = true

    
    var body: some View {
        VStack{
            NavigationBar(title: "添加设备", isBackBtnVisible: true, onBack: {
                navigator.pop()
            }, trailing:
                AnyView(
                    HStack {
                        Button(action: {
                            //navigator.presentSheet(.wifiInfo)
//                            navigator.push(.addingDevice)
                            navigator.push(.addDeviceList(peripheralIds: viewModel.founcPeripheralIds))
                            }, label: {
                                Image("ic_search")
                                    .resizable()
                                    .scaledToFit()
                                    .frame(width: 24, height: 24)
                            }).padding(.trailing, 12)
                        Button(action: {
                            navigator.push(.scannerContainer)
                        }, label: {
                            Image("scan")
                                .resizable()
                                .scaledToFit()
                                .frame(width: 24, height: 24)
                        }).padding(.trailing, 12)
                    }.padding(.trailing, 16)
                ))
            GeometryReader { geometry in
                ScrollView(.vertical, showsIndicators: false) {
                    VStack{
                        HStack{
                            RotatingScannerView(isAnimating: scanning, imageName: "search_device", size: 68)
                                .padding(.top, 24)
                                .padding(.leading, 16)
                               
                            VStack(alignment: .leading){
                                Spacer()
                                Text("正在搜索附近设备...".I18n)
                                    .font(.system(size: 16))
                                    .foregroundColor(AppColors.Gy1)
                                
                                Text("确保设备在附近并开启 配网状态".I18n)
                                    .font(.system(size: 14))
                                    .foregroundColor(AppColors.Gy2)
                                Spacer()
                            }.padding(.leading, 10)
                            Spacer()
                        }
                        LazyVStack{
                            ACollectionView(items: viewModel.foundPeripherals, content: { item in
                                HStack {
                                    AsyncImage(url: URL(string: item.cover)) { image in
                                        image.resizable()
                                            .scaledToFill()
                                            .frame(width: 40, height: 40)
                                            .clipped()
                                    } placeholder: {
                                        ProgressView()
                                            .frame(width: 40, height: 40)
                                    }.padding(.top, 12)
                                    VStack(alignment: .leading) {
                                        Text(item.pid)
                                            .font(.system(size: 14))
                                            .foregroundColor(AppColors.Gy1)
                                            .padding(.leading, 6)
                                            .padding(.top, 5)
                                        Text(item.name)
                                            .font(.system(size: 14))
                                            .foregroundColor(AppColors.Gy3)
                                            .padding(.bottom, 10)
                                            .padding(.top, 2)
                                            .padding(.leading, 6)
                                    }
                                }.frame(width: 173, height: 80)
                                    .background(AppColors.Gray1)
                                        .cornerRadius(12)
                                        
                            }
                              , onItemTap: { item in
                                // 点击事件处理
                                navigator.push(.addDeviceList(peripheralIds: viewModel.founcPeripheralIds))
                                
                            })
                            .padding(.horizontal, 12)
                            .padding(.top, 8)
                        }
                        ProductCategoryView( allow: $allowInnerScroll,viewModel: viewModel).frame(height: geometry.size.height)
                            .background(GeometryReader { geo in
                                Color.clear.preference(key: InnerScrollOffsetKey.self, value: geo.frame(in: .named("scroll")).minY)
                            })
                    }
                }
                .coordinateSpace(name: "scroll")
            }.onPreferenceChange(InnerScrollOffsetKey.self) { offset in
                if offset <= 0 {
                    // 说明顶部空白区域已滚完
                    allowInnerScroll = true
                } else {
                    allowInnerScroll = false
                }
            }
        }

    }
}

struct ACollectionView<Content: View>: View {
    let items: [Peripheral]?
    let content: (Peripheral) -> Content
    let onItemTap: (Peripheral) -> Void  // 点击事件的闭包
    
    init(items: [Peripheral]?, @ViewBuilder content: @escaping (Peripheral) -> Content, onItemTap: @escaping (Peripheral) -> Void) {
        self.items = items
        self.content = content
        self.onItemTap = onItemTap
    }
    
    var body: some View {
        LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 6) {
            if let items = items
            {
                ForEach(items) { item in
                    Button(action: {
                        onItemTap(item)  // 触发点击事件
                    }) {
                        content(item)  // 显示内容
                    }
                    .buttonStyle(PlainButtonStyle())  // 防止 Button 默认样式影响布局
                }
            }
        }
    }
}


